<?php
/**
 * @author kwor
 * @url http://www.kwor.cn
 *
 */
if (!defined('VALIDADMIN')) die ('Access Denied.');
/**
 *
 *
 * @return  bool
 **/
function chkcode($sn){
	if($sn==$_SESSION["keynum"]){
		return true;
	}else{
		return false;
	}
}


/**
 * 自动跳转
 * @param   string  string
 *
 * @return  void
 **/
function local_header($string, $replace = true, $http_response_code = 0)
{
	/*
	 if (strpos($string, '../upgrade/index.php') === 0)
	 {
	 echo '<script type="text/javascript">window.location.href="' . $string . '";</script>';
	 }
	 */
	$string = str_replace(array("\r", "\n"), array('', ''), $string);

	if (preg_match('/^\s*location:/is', $string))
	{
		@header('Location:'.$string . "\n", $replace);

		exit();
	}

	if (empty($http_response_code) || PHP_VERSION < '4.3')
	{
		@header('Location:'.$string, $replace);
	}
	else
	{
		@header('Location:'.$string, $replace, $http_response_code);
	}
}


/**
 * 创建编辑器
 * @param   string  input_name
 * @param   bool    add
 * @param   string  input_value ֵ
 * @param   string  Width
 * @param   string  Height
 */
function create_html_editor($input_name,$add, $input_value = '',$issmarty=true,$Width='95%',$Height='250')
{
	global $xueniao;
	if ($input_name=='fckeditor'){
		require_once("inc/editor/fckeditor/fckeditor.php");

		$editor = new FCKeditor($add);
		$editor->BasePath   = 'inc/editor/fckeditor/';
		$editor->Width      = $Width;
		$editor->Height     = $Height;
		$editor->ToolbarSet = 'Normal';
		$editor->Value      = $input_value;
		$myeditor = $editor->CreateHtml();
	}
	if($issmarty==true){
		$xueniao->assign($add, $myeditor);
	}else {
		return $myeditor;
	}
}



/**
 *
 * 创建上传文本框
 * @param $textname  //上传文本框id和名称（这是也是获取上传数据的地方）
 * @param $upprm     //上传页面
 * @param $defaultval  //默认值
 * @param $hassmall //为true说明有小图反之没有
 */
function create_uploadfile($textname='',$upprm='',$defaultbigval='',$smallbox='',$defaultsmallval='') {

	$iframename=$textname."_iframe";
	$showinputtextname=$textname;
	$formname=$textname.'_form'; //自动构建form名称
	$iframename=$textname.'_iframe';//自动构建对应的iframe
	$filename=$textname.'_input_file';//自动构建上传文本框名称
	$showwhere=$textname.'_div';//自动构建文本框名称

	$jsstr="<div id='$showwhere' name='$showwhere'></div>";
	$jsstr.="<script type='text/javascript'>
function uploadbox(){
var formname='$formname';
var hassmall='$smallbox'; 
var iframename='$iframename';
var filename='$filename';
var textname='$textname';
//创建容器
var div=document.createElement('div');";
	//插入上传界面代码
	$jsstr.="div.innerHTML=\"<iframe name='\"+iframename+\"' id='\"+iframename+\"' style='display:none'></iframe><form name='\"+formname+\"' enctype='multipart/form-data' method='post' target='\"+iframename+\"' action='$upprm?filename=\"+filename+\"&hassmall=\"+hassmall+\"'><input type='file' id='\"+filename+\"' name='\"+filename+\"'/><input type='submit' value='提交' /></form>\" ;";


	$jsstr.="div.innerHTML+=\"<input size='40' type='text' name='\"+textname+\"' id='\"+textname+\"' value='$defaultbigval' />\";";


	if($smallbox!==''){
		$jsstr.="div.innerHTML+=\"小图：<input size='40' type='text' name='\"+hassmall+\"' id='\"+hassmall+\"' value='$defaultsmallval' />\";";

	}
	//把加入容器加入子节点
	$jsstr.="document.getElementById('".$showwhere."').appendChild(div);
}
</script>";

	if($smallbox==''){
		$jsstr.='<script for="'.$iframename.'" event="onload">
  var cnt=document.frames["'.$iframename.'"].document.body.innerText;
  if(cnt!==\'\'&&cnt!==null){  document.getElementById("'.$showinputtextname.'").value=cnt; }  
  </script>';
	}else {
		$jsstr.='<script for="'.$iframename.'" event="onload">
  var cnt=document.frames["'.$iframename.'"].document.body.innerText;
  if(cnt!==\'\'&&cnt!==null){  
  var json=eval(\'(\'+cnt+\')\'); 
  document.getElementById("'.$showinputtextname.'").value=json.bigimg;
  document.getElementById("'.$smallbox.'").value=json.smallimg;
	}  
  </script>';
	}

	//自动加载
	$jsstr.="<script>window.onload=function(){uploadbox();}</script>";
	return $jsstr;
}




/**
 * 获取时间戳
 * @return  integer
 */
function gmtime()
{
	return (time() - date('Z'));
}

/**
 *获取系统时区
 * @return  integer
 */
function server_timezone()
{
	if (function_exists('date_default_timezone_get'))
	{
		return date_default_timezone_get();
	}
	else
	{
		return date('Z') / 3600;
	}
}

/**
 * 将时间戳转换为时间
 *local_date(date('Y-m-d'),'1283137716');
 *
 * @param  string       $format
 * @param  integer      $time
 *
 * @return  string
 */

function local_date($format, $time = NULL)
{
	$timezone = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone'];

	if ($time === NULL)
	{
		$time = gmtime();
	}
	elseif ($time <= 0)
	{
		return '';
	}

	$time += ($timezone * 3600);

	return date($format, $time);
}



/**
 * 获取客户浏览器信息
 * @return string
 */
function browseinfo() {
	$browser="";
	$browserver="";
	$Browsers =array("Lynx","MOSAIC","AOL","Opera","JAVA","MacWeb","WebExplorer","OmniWeb");
	$Agent = $_SERVER["HTTP_USER_AGENT"]?$_SERVER["HTTP_USER_AGENT"]:$HTTP_SERVER_VARS["HTTP_USER_AGENT"];
	for ($i=0; $i<=7; $i++) {
		if (strpos($Agent,$Browsers[$i])) {
			$browser = $Browsers[$i];
			$browserver ="";
		}
	}
	if (ereg("Mozilla",$Agent) && !ereg("MSIE",$Agent)) {
		$temp =explode("(", $Agent); $Part=$temp[0];
		$temp =explode("/", $Part); $browserver=$temp[1];
		$temp =explode(" ",$browserver); $browserver=$temp[0];
		$browserver =preg_replace("/([\d\.]+)/","\\1",$browserver);
		$browserver = " $browserver";
		$browser = "Netscape Navigator";
	}
	if (ereg("Mozilla",$Agent) && ereg("Opera",$Agent)) {
		$temp =explode("(", $Agent); $Part=$temp[1];
		$temp =explode(")", $Part); $browserver=$temp[1];
		$temp =explode(" ",$browserver);$browserver=$temp[2];
		$browserver =preg_replace("/([\d\.]+)/","\\1",$browserver);
		$browserver = " $browserver";
		$browser = "Opera";
	}
	if (ereg("Mozilla",$Agent) && ereg("MSIE",$Agent)) {
		$temp = explode("(", $Agent); $Part=$temp[1];
		$temp = explode(";",$Part); $Part=$temp[1];
		$temp = explode(" ",$Part);$browserver=$temp[2];
		$browserver =preg_replace("/([\d\.]+)/","\\1",$browserver);
		$browserver = " $browserver";
		$browser = "IE";
	}
	if ($browser!="") {
		$browseinfo = "$browser$browserver";
	}else {
		$browseinfo = "Unknown browse";
	}
	return $browseinfo;
}



/**
 * 获取操作系统信息
 * @return string
 */
function osinfo() {
	$os="";
	$Agent =$_SERVER["HTTP_USER_AGENT"]?$_SERVER["HTTP_USER_AGENT"]:$HTTP_SERVER_VARS["HTTP_USER_AGENT"];
	if (eregi('win',$Agent) && strpos($Agent, '95')) {
		$os="Windows 95";
	}elseif (eregi('win 9x',$Agent) && strpos($Agent, '4.90')) {
		$os="Windows ME";
	}elseif (eregi('win',$Agent) && ereg('98',$Agent)) {
		$os="Windows 98";
	}elseif (eregi('win',$Agent) && eregi('nt 5\.0',$Agent)) {
		$os="Windows 2000";
	}elseif (eregi('win',$Agent) && eregi('nt 5\.1',$Agent)) {
		$os="Windows XP";
	}elseif (eregi('win',$Agent) && eregi('nt',$Agent)) {
		$os="Windows NT";
	}elseif (eregi('win',$Agent) && ereg('32',$Agent)) {
		$os="Windows 32";
	}elseif (eregi('linux',$Agent)) {
		$os="Linux";
	}elseif (eregi('unix',$Agent)) {
		$os="Unix";
	}elseif (eregi('sun',$Agent) && eregi('os',$Agent)) {
		$os="SunOS";
	}elseif (eregi('ibm',$Agent) && eregi('os',$Agent)) {
		$os="IBM OS/2";
	}elseif (eregi('Mac',$Agent) && eregi('PC',$Agent)) {
		$os="Macintosh";
	}elseif (eregi('PowerPC',$Agent)) {
		$os="PowerPC";
	}elseif (eregi('AIX',$Agent)) {
		$os="AIX";
	}elseif (eregi('HPUX',$Agent)) {
		$os="HPUX";
	}elseif (eregi('NetBSD',$Agent)) {
		$os="NetBSD";
	}elseif (eregi('BSD',$Agent)) {
		$os="BSD";
	}elseif (ereg('OSF1',$Agent)) {
		$os="OSF1";
	}elseif (ereg('IRIX',$Agent)) {
		$os="IRIX";
	}elseif (eregi('FreeBSD',$Agent)) {
		$os="FreeBSD";
	}
	if ($os=='') $os = "Unknown OS";
	return $os;
}

/**
 * 获取真实ip
 * @access  public
 * @return  string
 */
function real_ip()
{
	static $realip = NULL;

	if ($realip !== NULL)
	{
		return $realip;
	}

	if (isset($_SERVER))
	{
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
		{
			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

			foreach ($arr AS $ip)
			{
				$ip = trim($ip);

				if ($ip != 'unknown')
				{
					$realip = $ip;

					break;
				}
			}
		}
		elseif (isset($_SERVER['HTTP_CLIENT_IP']))
		{
			$realip = $_SERVER['HTTP_CLIENT_IP'];
		}
		else
		{
			if (isset($_SERVER['REMOTE_ADDR']))
			{
				$realip = $_SERVER['REMOTE_ADDR'];
			}
			else
			{
				$realip = '0.0.0.0';
			}
		}
	}
	else
	{
		if (getenv('HTTP_X_FORWARDED_FOR'))
		{
			$realip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_CLIENT_IP'))
		{
			$realip = getenv('HTTP_CLIENT_IP');
		}
		else
		{
			$realip = getenv('REMOTE_ADDR');
		}
	}

	preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
	$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

	return $realip;
}



/**
 * url构建，避免静态化造成的url失效问题
 * @param $params
 * @param $trueurl
 * @param $urlname
 */
function bulider_url($params,$trueurl,$urlname='htm') {
	if($type!==false && $type!=="" ){
		$showurl="$trueurl/%sshow.".$urlname;
		if(!is_array($params)){
			$fields=$params;
		}else{
			foreach ($params as $k => $v) {
				$fields.= "$k-$v-";
			}
		}
		$showurl = sprintf( $showurl,$fields);
	}else {
		$showurl=$trueurl;
	}
	return $showurl;
}



/**
 * 获取指定文件夹得下级文件夹名称
 * @param string $dir
 * 数组的键值都是文件夹名
 */
function get_dirname($dir) {
	$all_dir=array();
	$handle = @opendir($dir);
	while (false!==($on_dir = @readdir($handle))) {
		if (strpos($on_dir,'.')===false )
		{
			$all_dir[$on_dir]=$on_dir;
		}
	}
	@closedir($handle);
	return $all_dir;
}


/**
 *
 * 伪静态php获取数据实现，主要为避免服务器不支持伪静态规则
 *
 * @ /test.php/goods-30-show.htm
 * @ $_GET['goods']
 */
function rewrite(){
	global $_GET;
	$nav=$_SERVER["REQUEST_URI"];
	$script_name=$_SERVER["SCRIPT_NAME"];
	$nav=substr(ereg_replace("^$script_name","",urldecode($nav)),1);
	$vars = explode('-',$nav);

	for($i=0;$i<Count($vars);$i+=2){
		$_GET["$vars[$i]"]=$vars[$i+1];
	}
	return $_GET;
}



/**
 * 检查目标文件夹是否存在，如果不存在则自动创建该目录
 *
 * @access      public
 * @param       string      folder     目录路径。不能使用相对于网站根目录的URL
 *
 * @return      bool
 */
function make_dir($folder)
{
	$reval = false;

	if (!file_exists($folder))
	{
		/* 如果目录不存在则尝试创建该目录 */
		@umask(0);

		/* 将目录路径拆分成数组 */
		preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);

		/* 如果第一个字符为/则当作物理路径处理 */
		$base = ($atmp[0][0] == '/') ? '/' : '';

		/* 遍历包含路径信息的数组 */
		foreach ($atmp[1] AS $val)
		{
			if ('' != $val)
			{
				$base .= $val;

				if ('..' == $val || '.' == $val)
				{
					/* 如果目录为.或者..则直接补/继续下一个循环 */
					$base .= '/';

					continue;
				}
			}
			else
			{
				continue;
			}

			$base .= '/';

			if (!file_exists($base))
			{
				/* 尝试创建目录，如果创建失败则继续循环 */
				if (@mkdir(rtrim($base, '/'), 0777))
				{
					@chmod($base, 0777);
					$reval = true;
				}
			}
		}
	}
	else
	{
		/* 路径已经存在。返回该路径是不是一个目录 */
		$reval = is_dir($folder);
	}

	clearstatcache();

	return $reval;
}

/**
 *
 * 创建（是否）类型的下拉菜单
 * @param $selectboxname
 * @param $selectval
 */
function true_false_select($selectboxname,$selectval='N') {
	$optinstr="<select name='".$selectboxname."' id='".$selectboxname."' >";
	if($selectval=='N')
	{
		$optinstr.="<option value='N' selected>否</option>";
		$optinstr.="<option value='Y'>是</option>";
	}else {
		$optinstr.="<option value='Y' selected>是</option>";
		$optinstr.="<option value='N'>否</option>";
	}

	$optinstr.="</select > ";
	return $optinstr;
}

function thtime($totime) {
	$t=explode(' ', $totime);
	$x=explode(':', $t[1]);
	$strtime=$t[0]."-".$x[0]."-".$x[1]."-".$x[2];
	$jstr='<script language="javascript">';
	$jstr.='function time()
{  
var now,h,m,s;  
now=new Date();  
h = now.getHours();  
m =now.getMinutes();  
s = now.getSeconds();  
if(h<10) h="0"+h;  
if(m<10) m="0"+m;  
if(s<10) s="0"+s;  
document.getElementById("time").innerHTML=""+ h + ":" + m + ":" + s;  
setTimeout("time();", 1000);  
}  ';

	$jstr.='
var strm1="'.$strtime.'";
function timem1()  
{
var arr1=strm1.split("-");   
var now1=new Date(arr1[0],arr1[1],arr1[2],arr1[3],arr1[4],arr1[5]); 
 
var now=new Date(); 
var h,m,s,dif;
now.setMonth(now.getMonth()+1);
dif= now1.getTime()-now.getTime(); 
h = dif / (60 * 60 * 1000); 
m = (dif % (60 * 60 * 1000))/(60 * 1000);
s = ((dif % (60 * 60 * 1000))%(60 * 1000))/1000;
if(dif>0)
{';
	$jstr.=" document.getElementById('counter').innerHTML='<li><span>'+parseInt(h)+'</span>小时</li><li><span>' + parseInt(m) + '</span>分钟</li><li><span>'+ parseInt(s) +'</span>秒</li> ';";
	$jstr.='setTimeout("timem1()", 1000);}else{';
	$jstr.='document.getElementById("counter").innerHTML="<li>团购已结束</li>";}}';
	$jstr.=' window.onload=time;
              window.onload=timem1;';
	$jstr.='</script>';
	$jstr.='<div id="time"></div>';
	$jstr.='<ul id="counter"></ul>';

	return $jstr;
}


/**
 * 获取城市数组（html_select）
 * $addkey    自己添加的选项名称
 * $addval    自己添加的选项值
 */
function get_citylist($addkey='',$addval='',$type='') {
	$sql='select name,id from sn_city where is_close = "N"';
	$cityarr=$GLOBALS[db]->getlist($sql);
	if($addkey!==""){
		$new[$addval]=$addkey;	//注意此处是相反的
	}
	if($type==''){
		foreach ($cityarr as $key => $value) {

			$new[$cityarr[$key]['id']]=$cityarr[$key]['name'];

		}
	}else if($type=='name'){
		foreach ($cityarr as $key => $value) {

			$new[$cityarr[$key]['name']]=$cityarr[$key]['name'];

		}
	}

	return $new;
}

//name获取城市id
function get_cityid_byname($val){
	$sql="select * from sn_city where name= '".$val."'";
	$resid=$GLOBALS[db]->getrow($sql);
	return $resid['id'];
}

//id获取城市名称name
function get_cityname_byid($val){
	$sql="select * from sn_city where id= '".$val."'";
	$resid=$GLOBALS[db]->getrow($sql);
	return $resid['name'];
}




//邮件发送
function sendmail($smtps,$semail,$semailuser,$semailpass,$toemail,$mailtitle,$mailcount,$mmailtype='HTML',$smtpp=25) {
	//##########################################
	$smtpserver = $smtps;//SMTP服务器
	$smtpserverport =$smtpp;//SMTP服务器端口
	$smtpusermail = $semail;//SMTP服务器的用户邮箱
	$smtpemailto = $toemail;//发送给谁
	$smtpuser = $semailuser;//SMTP服务器的用户帐号
	$smtppass = $semailpass;//SMTP服务器的用户密码
	$mailsubject = $mailtitle;//邮件主题
	$mailbody = $mailcount;//邮件内容
	$mailtype = $mmailtype;//邮件格式（HTML/TXT）,TXT为文本邮件
	##########################################
	$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
	$smtp->debug = FALSE;//是否显示发送的调试信息
	$res=$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
	return $res;
}




//生成指定位数的随机数
function randomkeys($length)
{
	$pattern = "1234567890";
	for($i=0;$i<$length;$i++)
	{
		$key .= $pattern{rand(0,10)};
   }
   return $key;
  }



?>